<template>
  <div class="dictionary">
    <!-- 字典类型选择 -->
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-list-ul"></i> 字典类型
        </h5>
      </div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-4">
            <select class="form-select" v-model="selectedDictType" @change="handleDictTypeChange">
              <option value="">请选择字典类型</option>
              <option v-for="type in dictTypes" :key="type.code" :value="type.code">
                {{ type.name }}
              </option>
            </select>
          </div>
          <div class="col-md-8">
            <button 
              class="btn btn-primary me-2" 
              @click="showAddModal"
              :disabled="!selectedDictType"
            >
              <i class="bi bi-plus-lg me-2"></i>新增字典项
            </button>
            <button 
              class="btn btn-outline-secondary" 
              @click="handleRefresh"
              :disabled="loading"
            >
              <i class="bi bi-arrow-clockwise me-2"></i>刷新
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 字典项列表 -->
    <div class="card" v-if="selectedDictType">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">
          <i class="bi bi-table"></i> {{ getCurrentDictTypeName() }} - 字典项列表
        </h5>
        <span class="text-muted">共 {{ dictItems.length }} 项</span>
      </div>
      <div class="card-body">
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2 text-muted">正在加载字典数据...</p>
        </div>

        <!-- 数据表格 -->
        <div v-else-if="dictItems.length > 0" class="table-responsive-wrapper">
          <div class="table-responsive">
            <table class="table table-hover table-nowrap">
            <thead class="table-light">
              <tr>
                <th width="15%">字典编码</th>
                <th width="35%">字典内容</th>
                <th width="10%">排序</th>
                <th width="10%">状态</th>
                <th width="15%">更新时间</th>
                <th width="15%">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in dictItems" :key="item.id">
                <td>
                  <code class="text-primary">{{ selectedDictType }}</code>
                </td>
                <td>{{ item.name }}</td>
                <td>
                  <span class="badge bg-secondary">{{ item.sort }}</span>
                </td>
                <td>
                  <span :class="item.status === 'active' ? 'badge bg-success' : 'badge bg-danger'">
                    {{ item.status === 'active' ? '启用' : '禁用' }}
                  </span>
                </td>
                <td>{{ formatDate(item.updateTime) }}</td>
                <td>
                  <div class="btn-group btn-group-sm">
                    <button 
                      class="btn btn-outline-primary" 
                      @click="editItem(item)"
                      title="编辑"
                    >
                      <i class="bi bi-pencil"></i>
                    </button>
                    <button 
                      class="btn btn-outline-warning" 
                      @click="toggleStatus(item)"
                      :title="item.status === 'active' ? '禁用' : '启用'"
                    >
                      <i :class="item.status === 'active' ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
                    </button>
                    <button 
                      class="btn btn-outline-danger" 
                      @click="deleteItem(item)"
                      title="删除"
                    >
                      <i class="bi bi-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="text-center py-5">
          <i class="bi bi-inbox display-1 text-muted"></i>
          <p class="mt-3 text-muted">暂无字典项数据</p>
          <button class="btn btn-primary" @click="showAddModal">
            <i class="bi bi-plus-lg me-2"></i>添加第一个字典项
          </button>
        </div>
      </div>
    </div>

    <!-- 空状态 - 未选择字典类型 -->
    <div v-else class="text-center py-5">
      <i class="bi bi-book display-1 text-muted"></i>
      <p class="mt-3 text-muted">请先选择字典类型</p>
    </div>

    <!-- 新增/编辑模态框 -->
    <div class="modal fade" id="dictModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-plus-circle"></i> {{ isEdit ? '编辑' : '新增' }}字典项
            </h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <form @submit.prevent="handleSubmit">
            <div class="modal-body">
              <div class="mb-3">
                <label for="dictCode" class="form-label">字典编码</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="dictCode" 
                  :value="selectedDictType"
                  disabled
                  placeholder="字典编码"
                >
                <div class="form-text">字典编码由系统自动分配</div>
              </div>
              <div class="mb-3">
                <label for="dictName" class="form-label">字典内容 <span class="text-danger">*</span></label>
                <textarea 
                  class="form-control" 
                  id="dictName" 
                  v-model="formData.name"
                  rows="4"
                  required
                  placeholder="请输入字典内容"
                  style="min-height: 120px;"
                ></textarea>
              </div>
              <div class="row">
                <div class="col-md-6">
                  <label for="dictSort" class="form-label">排序</label>
                  <input 
                    type="number" 
                    class="form-control" 
                    id="dictSort" 
                    v-model.number="formData.sort"
                    min="0"
                    placeholder="排序值"
                  >
                </div>
                <div class="col-md-6">
                  <label for="dictStatus" class="form-label">状态</label>
                  <select class="form-select" id="dictStatus" v-model="formData.status">
                    <option value="active">启用</option>
                    <option value="inactive">禁用</option>
                  </select>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="submitting">
                <span v-if="submitting" class="spinner-border spinner-border-sm me-2"></span>
                {{ isEdit ? '更新' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
      <div class="modal-dialog modal-sm">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-exclamation-triangle text-warning"></i> 确认删除
            </h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <p>确定要删除字典项 <strong>{{ deleteTarget?.name }}</strong> 吗？</p>
            <p class="text-muted small">此操作不可撤销，请谨慎操作。</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-danger" @click="confirmDelete" :disabled="submitting">
              <span v-if="submitting" class="spinner-border spinner-border-sm me-2"></span>
              确认删除
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Modal } from 'bootstrap'
import api from '@/utils/api'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const selectedDictType = ref('')
const dictTypes = ref([])
const dictItems = ref([])
const isEdit = ref(false)
const deleteTarget = ref(null)

// 表单数据
const formData = ref({
  name: '',
  sort: 0,
  status: 'active'
})

// 模态框实例
let dictModal = null
let deleteModal = null

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 获取当前字典类型名称
const getCurrentDictTypeName = () => {
  const type = dictTypes.value.find(t => t.code === selectedDictType.value)
  return type ? type.name : ''
}

// 加载字典类型
const loadDictTypes = async () => {
  try {
    const response = await api.post('/api/Dict/get-dict-categories')
    if (response.data) {
      // 转换数据格式以适配前端组件
      dictTypes.value = response.data.map(item => ({
        code: item.dictId.toString(),
        name: item.dictName,
        itemCount: item.itemCount
      }))
    }
  } catch (error) {
    console.error('加载字典类型出错:', error)
    dictTypes.value = []
  }
}

// 加载字典项
const loadDictItems = async () => {
  if (!selectedDictType.value) {
    dictItems.value = []
    return
  }
  
  loading.value = true
  try {
    const response = await api.post('/api/Dict/get-by-dict-id', {
      dictId: parseInt(selectedDictType.value)
    })
    
    if (response.data) {
      // 转换数据格式以适配前端组件
      dictItems.value = response.data.map(item => ({
        id: item.id,
        code: item.itemValue,
        name: item.itemName,
        value: item.itemValue,
        sort: parseInt(item.itemValue) || 0,
        status: 'active', // 默认状态，因为数据库中没有状态字段
        updateTime: item.inputDate
      }))
    }
  } catch (error) {
    console.error('加载字典项出错:', error)
    dictItems.value = []
  } finally {
    loading.value = false
  }
}

// 字典类型变化处理
const handleDictTypeChange = () => {
  loadDictItems()
}

// 刷新数据
const handleRefresh = () => {
  loadDictItems()
}

// 显示新增模态框
const showAddModal = () => {
  isEdit.value = false
  formData.value = {
    name: '',
    sort: dictItems.value.length + 1,
    status: 'active'
  }
  dictModal.show()
}

// 编辑字典项
const editItem = (item) => {
  isEdit.value = true
  formData.value = { ...item }
  dictModal.show()
}

// 切换状态
const toggleStatus = async (item) => {
  try {
    const newStatus = item.status === 'active' ? 'inactive' : 'active'
    
    // 模拟API调用
    console.log('切换状态:', item.id, newStatus)
    
    // 更新本地状态
    item.status = newStatus
    item.updateTime = new Date().toISOString()
    
    showToast(`${item.name} 已${newStatus === 'active' ? '启用' : '禁用'}`, 'success')
  } catch (error) {
    console.error('切换状态失败:', error)
    showToast('操作失败', 'error')
  }
}

// 删除字典项
const deleteItem = (item) => {
  deleteTarget.value = item
  deleteModal.show()
}

// 确认删除
const confirmDelete = async () => {
  if (!deleteTarget.value) return
  
  submitting.value = true
  try {
    // 调用删除API
    await api.delete(`/api/Dict/${deleteTarget.value.id}`)
    
    // 从列表中移除
    const index = dictItems.value.findIndex(item => item.id === deleteTarget.value.id)
    if (index > -1) {
      dictItems.value.splice(index, 1)
    }
    
    deleteModal.hide()
    showToast(`${deleteTarget.value.name} 已删除`, 'success')
    deleteTarget.value = null
  } catch (error) {
    console.error('删除失败:', error)
    showToast('删除失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  submitting.value = true
  try {
    if (isEdit.value) {
      // 更新字典项
      await api.post('/api/Dict/update', {
        id: formData.value.id,
        dictId: parseInt(selectedDictType.value),
        dictName: getCurrentDictTypeName(),
        itemName: formData.value.name,
        itemValue: formData.value.value
      })
      
      showToast('字典项更新成功', 'success')
    } else {
      // 新增字典项
      await api.post('/api/Dict', {
        dictId: parseInt(selectedDictType.value),
        dictName: getCurrentDictTypeName(),
        itemName: formData.value.name,
        itemValue: formData.value.value
      })
      
      showToast('字典项添加成功', 'success')
    }
    
    dictModal.hide()
    // 重新加载字典项数据
    await loadDictItems()
  } catch (error) {
    console.error('保存失败:', error)
    showToast('保存失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 显示Toast消息
const showToast = (message, type = 'info') => {
  console.log(`Toast [${type}]: ${message}`)
}

// 组件挂载时初始化
onMounted(() => {
  // 初始化模态框
  const dictModalElement = document.getElementById('dictModal')
  const deleteModalElement = document.getElementById('deleteModal')
  
  if (dictModalElement) {
    dictModal = new Modal(dictModalElement)
  }
  
  if (deleteModalElement) {
    deleteModal = new Modal(deleteModalElement)
  }
  
  // 加载字典类型
  loadDictTypes()
})
</script>

<style scoped>
.dictionary {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.card {
  border: none;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
}

.table th {
  font-weight: 600;
  color: #495057;
  border-top: none;
}

.table td {
  vertical-align: middle;
}

.btn-group-sm .btn {
  padding: 0.25rem 0.5rem;
}

.text-truncate {
  cursor: help;
}

code {
  font-size: 0.875em;
  color: #e83e8c;
  background-color: #f8f9fa;
  padding: 0.125rem 0.25rem;
  border-radius: 0.25rem;
}

.form-text {
  font-size: 0.875rem;
  color: #6c757d;
}

.modal-body .form-label {
  font-weight: 500;
}

.modal-body .text-danger {
  color: #dc3545 !important;
}

/* 响应式优化 */
@media (max-width: 1200px) {
  .dictionary {
    padding: 0.75rem;
  }
}

@media (max-width: 768px) {
  .dictionary {
    padding: 0.5rem;
  }
  
  .card-body {
    padding: 0.75rem;
  }
  
  .table th,
  .table td {
    padding: 0.5rem 0.25rem;
    font-size: 0.8rem;
  }
  
  .btn-group-sm .btn {
    padding: 0.2rem 0.4rem;
    font-size: 0.75rem;
  }
  
  .modal-dialog {
    margin: 0.5rem;
    max-width: calc(100% - 1rem);
  }
  
  .modal-body {
    padding: 1rem;
  }
}

@media (max-width: 576px) {
  .dictionary {
    padding: 0.25rem;
  }
  
  .card-body {
    padding: 0.5rem;
  }
  
  .table th,
  .table td {
    padding: 0.375rem 0.2rem;
    font-size: 0.75rem;
  }
  
  .btn-group-sm .btn {
    padding: 0.15rem 0.3rem;
    font-size: 0.7rem;
  }
  
  .card-title {
    font-size: 1rem;
  }
  
  .modal-dialog {
    margin: 0.25rem;
    max-width: calc(100% - 0.5rem);
  }
  
  .modal-body {
    padding: 0.75rem;
  }
  
  .form-label {
    font-size: 0.85rem;
  }
}

/* 表格水平滚动优化 */
.table-responsive-wrapper {
  position: relative;
}

.table-responsive {
  border-radius: 0.375rem;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05);
}

.table-nowrap {
  min-width: 700px;
}

.table-nowrap th,
.table-nowrap td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table-nowrap th:first-child,
.table-nowrap td:first-child {
  position: sticky;
  left: 0;
  background: white;
  z-index: 10;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.table-nowrap th:last-child,
.table-nowrap td:last-child {
  position: sticky;
  right: 0;
  background: white;
  z-index: 10;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
}
</style>